package com.zyx.camunda.helpers.listener;

import cn.hutool.core.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.impl.history.event.HistoryEvent;
import org.camunda.bpm.engine.impl.history.event.HistoryEventTypes;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.spring.boot.starter.event.ExecutionEvent;
import org.camunda.bpm.spring.boot.starter.event.TaskEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * <a href="http://camunda-cn.shaochenfeng.com/user-guide/spring-boot-integration/the-spring-event-bridge/">Event总线</a>
 *
 * @author zyx
 * @since 2023/9/27 19:22
 */
@Component
@Slf4j
public class CamundaEventListener {
    @EventListener
    public void onTaskEvent(DelegateTask taskDelegate) {
        // 处理可变的任务事件
    }

    @EventListener
    public void onTaskEvent(TaskEvent taskEvent) {
        // 处理不可变的任务事件
    }

    @EventListener
    public void onExecutionEvent(DelegateExecution executionDelegate) {
        // 处理可变的执行事件
        // 监听任务完成，ActivityImpl与ProcessDefinitionEntity均会回调
        // 为了避免重复事件，这里只监听ProcessDefinitionEntity的回调
        log.info("=====>>>>> executionDelegate.getEventName(): {} <<<<<=====", executionDelegate.getEventName());
        Object eventSource = ReflectUtil.getFieldValue(executionDelegate, "eventSource");
        if (Objects.nonNull(eventSource) && eventSource instanceof ProcessDefinitionEntity
            // && HistoryEventTypes.PROCESS_INSTANCE_END.getEventName().equals(executionDelegate.getEventName())
        ) {
            log.info("==================== executionDelegate 回调 ====================");
            log.info("=====>>>>> executionDelegate.getClass(): {} <<<<<=====", executionDelegate.getClass());
            log.info("=====>>>>> executionDelegate.getEventName(): {} <<<<<=====", executionDelegate.getEventName());
            log.info("=====>>>>> executionDelegate.getProcessInstanceId() {} <<<<<=====", executionDelegate.getProcessInstanceId());
            log.info("=====>>>>> executionDelegate.getCurrentActivityName(): {} <<<<<=====", executionDelegate.getCurrentActivityName());
            log.info("=====>>>>> executionDelegate.getBpmnModelElementInstance().getElementType().getTypeName(): {} <<<<<=====",
                executionDelegate.getBpmnModelElementInstance().getElementType().getTypeName());
        }
    }

    @EventListener
    public void onExecutionEvent(ExecutionEvent executionEvent) {
        // 处理不可改的执行事件
    }

    @EventListener
    public void onHistoryEvent(HistoryEvent historyEvent) {
        // 处理历史事件

    }

}
